package com.om.authing.collection;

import Utils.HttpClientUtils;
import cn.authing.core.mgmt.ManagementClient;
import cn.authing.core.types.LogsPageParam;
import cn.authing.core.types.UserAction;
import cn.authing.core.types.UserActions;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import java.util.List;
import java.util.Map;

public class UserActionLog {
    public static ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) {
        String userPoolId = args[0];
        String secret = args[1];
        int pageSize = Integer.parseInt(args[2]);
        String indexName = args[3];

        ManagementClient managementClient = new ManagementClient(userPoolId, secret);
        getLog(managementClient, 1, pageSize, indexName);
    }

    private static void getLog(ManagementClient managementClient, int page, int pageSize, String indexName) {
        try {
            UserActions execute = managementClient
                    .statistics()
                    .listUserActions(new LogsPageParam(null, null, null, page, pageSize))
                    .execute();
            List<UserAction> list = execute.getList();
            parseLog(list, indexName);

            int totalCount = execute.getTotalCount();
            System.out.println("****** totalCount: " + totalCount);
            int totalPage = (totalCount / pageSize) + 1;
            System.out.printf("****** page: %d/%d%n", page, totalPage);

            while (page < totalPage) {
                page += 1;
                execute = managementClient
                        .statistics()
                        .listUserActions(new LogsPageParam(null, null, null, page, pageSize))
                        .execute();
                parseLog(execute.getList(), indexName);
                System.out.printf("****** page: %d/%d%n", page, totalPage);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void parseLog(List<UserAction> list, String indexName) throws Exception {
        RestHighLevelClient restHighLevelClient = HttpClientUtils.restClient();
        BulkRequest request = new BulkRequest();

        for (UserAction userAction : list) {
            Map map = objectMapper.convertValue(userAction, Map.class);
            String logId = (String) map.get("logId");
            request.add(new IndexRequest(indexName, "_doc", logId).source(map));
        }
        if (request.requests().size() != 0) restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        restHighLevelClient.close();
    }
}
